package loginlog

import (
	"encoding/json"
	"os"
	"path/filepath"
	"sync"

	"gitee.com/tomatomeatman/golang-repository/bricks3/utils/app/moduleutil"
	Log "github.com/cihub/seelog"
)

var (
	businessInfo     *BusinessInfo
	businessInfoOnce sync.Once
)

type BusinessInfo struct {
	DbName    string `json:"dbName"`    //所用库
	TableName string `json:"tableName"` //所用表名",
	// Id         string `json:"sId"`         //记录编号字段名",
	// Name       string `json:"sName"`       //用户名字段名",
	// No         string `json:"sNo"`         //用户唯一标识字段名",
	// Pass       string `json:"sPass"`       //用户密码字段名",
	// Type       string `json:"sType"`       //类型",
	// State      string `json:"iState"`      //账户状态字段名",
	// StateValue string `json:"iStateValue"` //有效状态值",
}

func GetBusinessInfo() *BusinessInfo {
	businessInfoOnce.Do(func() {
		root := ""
		exePath, err := os.Executable()
		if err != nil {
			root = "."
		}

		root, _ = filepath.EvalSymlinks(filepath.Dir(exePath))

		business := filepath.Join(root, "config/LoginLogBusiness.json")

		if _, err := os.Stat(business); os.IsNotExist(err) {
			Log.Error("业务配置文件不存在:", "config/LoginLogBusiness.json")
			return
		}

		data, err := os.ReadFile(business)
		if err != nil {
			Log.Error("读取配置文件发生异常:", err)
			return
		}

		temp := BusinessInfo{}
		err = json.Unmarshal(data, &temp)
		if err != nil {
			Log.Error("配置信息转实体发生异常:", err)
			return
		}

		businessInfo = &temp
	})

	if businessInfo == nil {
		businessInfo = &BusinessInfo{
			DbName:    moduleutil.GetMainDb(),
			TableName: "LoginLog",
		}
	}

	return businessInfo
}
